package com.github.roc.security.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.github.roc.security.web.dto.User;
import com.github.roc.security.web.dto.UserQueryCondition;
import com.github.roc.security.web.exception.UserNotExistException;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述: user
 * 包名: com.github.roc.security.web
 * 作者: ChenGuop.
 * 日期: 2018/10/15 上午10:23.
 * 项目名称: security-oam
 * 版本: 1.0
 * JDK: since 1.8
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@PostMapping
	@ApiOperation(value = "创建用户")
	public User create(@Valid @RequestBody User user) {
		System.out.println(user);
    user.setId("1");
//    System.out.println(ReflectionToStringBuilder.toString(user, ToStringStyle.MULTI_LINE_STYLE));
    return user;
  }

	@PutMapping("/{id:\\d+}")
  @ApiImplicitParam(name = "id", value= "用户id", dataType = "Integer", paramType = "path")
	public User update(@Valid @RequestBody User user, BindingResult errors) throws Exception {

//	  if (errors.hasErrors()){
//
//    }
		System.out.println(user.getId());
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(user.getBirthday());

		user.setId("1");
		return user;
	}

	@DeleteMapping("/{id:\\d+}")
	public void delete(@PathVariable String id) throws UserNotExistException {
    System.out.println(id);
    throw new UserNotExistException(id);
	}

	@GetMapping
	@JsonView(User.UserSimpleView.class)
	@ApiOperation(value = "用户查询服务")
	public List<User> query(UserQueryCondition condition,
                          @PageableDefault(page = 2, size = 17, sort = "username,asc") Pageable pageable) {

//		System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE));

		System.out.println(pageable.getPageSize());
		System.out.println(pageable.getPageNumber());
		System.out.println(pageable.getSort());

		List<User> users = new ArrayList<>();
		users.add(new User());
		users.add(new User());
		users.add(new User());
		return users;
	}

	@GetMapping("/{id:\\d+}")
	@JsonView(User.UserDetailView.class)
	public User getInfo(@ApiParam("用户id") @PathVariable String id) {
//		throw new RuntimeException("user not exist");
		System.out.println("进入getInfo服务");
		User user = new User();
		user.setUsername("tom");
		return user;
	}
}
